<?php
    /**
     * Created by PhpStorm.
     * User: huangzhongwei
     * Date: 2018/10/15
     * Time: 19:41
     */

    namespace app\api\controller;

    use app\common\model\AdminLogin as adminLoginModel;
    use app\lib\exception\MissException;
    use app\lib\exception\PasswordException;
    use app\api\service\Token;
    use app\lib\exception\SuccessMessage;
    use think\Cache;

    class AdminLogin extends BaseController
    {
        public function verify()
        {


            $data = request()->param();

            $account = adminLoginModel::where('app_id', $data['userName'])->find();

            if (!$account) {
                return new MissException(['msg' => '账号不存在', 'errorCode' => "40000"]);
            }

            if ($account['app_secret'] != setPassword($data['password'])) {
                return new PasswordException();
            }

            $scope            = $account->scope;
            $uid              = $account->id;
            $values           = [
                'scope' => $scope,
                'uid'   => $uid,
            ];
            $token            = $this->saveToCache($values);
            $account['token'] = $token;
            return $account;
        }


        private function saveToCache($values)
        {
            $token     = Token::generateToken();
            $expire_in = config('setting.token_expire_in');
            $result    = cache($token, json_encode($values), $expire_in);
            if (!$result) {
                throw new TokenException([
                                             'msg'       => '服务器缓存异常',
                                             'errorCode' => 10005,
                                         ]);
            }
            return $token;
        }

        public function loginOut()
        {
            $data  = request()->param();
            $token = $data['token'];
            if (Token::verifyToken($token)) {
                cache($token, null);
            }
            return new SuccessMessage();
        }
    }